const Koa=require('koa')
const Router=require('koa-router')
const serve=require('koa-static')
const parser=require('koa-bodyparser')
const {exec}=require('./db')
const jwt=require('jsonwebtoken')
const key='ww'

const app=new Koa()
const router=new Router()
app.use(parser())
app.use(serve(__dirname + '/views'))

router.post('/login',async ctx=>{
   const {userName,passWord}=ctx.request.body
   const data=await exec(`select * from goods where userName='${userName}' and passWord='${passWord}'`)
//    console.log(data)
    if(data.length>0){
        const token=jwt.sign({
            userName:data[0].userName,
            userId:data[0].userId
        },key,{
            expiresIn:'10h'
        })
        ctx.body={
            message:'登录成功',
            token 
        }
    }else{
     const data=await exec(`insert into goods (userName,passWord,userId) values ('${userName}','${passWord}',0)`)
      ctx.body={
        message:'账号密码不匹配',
      }
    } 
})

//获取列表
router.get('/getlist',async ctx=>{
    // console.log(ctx.request.query);
    const {token}=ctx.request.query
    const data=await exec('select * from goodlogin')
    if(token){
        if(jwt.verify(token,key)){
            ctx.body={
                   message:'获取成功',
                   data
               }
        }else{
            ctx.body={
                message:'登录信息过期',
               
            }
        }
    }else{
        ctx.body={
            message:'请先登录'
        }
    }
    // console.log(data)
   
})

app.use(router.routes())
app.listen(5678,()=>{
    console.log('启动http://127.0.0.1:5678');
})